package com.tanhua.admin.listener;

/**
 * @Author: cl
 * @Date: 2022/5/17 - 05 - 17
 * @Description:
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.Log;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 监听mq消息
 */
@Component
public class LogListener {

    @Autowired
    private LogMapper logMapper;

    //
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "tanhua.log.queue", durable = "true"),//队列名字
            exchange = @Exchange(value = "tanhua.log.exchange", type = ExchangeTypes.TOPIC),//交换机名字
            key = {"log.*"}//key
    ))
    public void listenCreate(String message) {

        try {
            //1、解析放入的json字符串
            Map<String, Object> map = JSON.parseObject(message, Map.class);
            //2、获取存入的数据
            Long userId = Long.valueOf(map.get("userId").toString());
            String type = (String) map.get("type");
            String logTime = (String) map.get("logTime");
            String busId = (String) map.get("busId");
            //3、将数据保存到数据库
            Log log = new Log(userId, logTime, type);
            logMapper.insert(log);

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}
